package org.will.ftppool;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @Author wangwei-ww
 * @Date 2017/6/29 11:52
 * @Comment
 */
public class FTPClientFactory extends BasePoolableObjectFactory<FTPClient> {
    private static Logger logger = LoggerFactory.getLogger("ftp-pool");
    private FTPConfig config;

    public FTPClientFactory(FTPConfig config) {
        this.config = config;
    }

    @Override
    public FTPClient makeObject() throws Exception {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(config.getClientTimeout());
        try {
            ftpClient.connect(config.getHost(), config.getPort());
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                logger.warn("FTPServer refused connection");
                return null;
            }
            boolean result = ftpClient.login(config.getUsername(), config.getPassword());
            if (!result) {
                throw new FTPClientException("+++++++++++++ ftpClient登陆失败! +++++++++++++++" + config);
            }
            ftpClient.setFileType(config.getTransferFileType());
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding(config.getEncoding());
            if (config.getPassiveMode()) {
                ftpClient.enterLocalPassiveMode();
            }
        } catch (Exception e) {
            logger.error("FTPClientFactory->makeObject error", e);
        }
        return ftpClient;
    }

    @Override
    public void destroyObject(FTPClient ftpClient) throws Exception {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.logout();
            }
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException io) {
                io.printStackTrace();
            }
        }
    }

    @Override
    public boolean validateObject(FTPClient ftpClient) {
        logger.info("-------------FTPClientFactory validateObject---------------");
        try {
            return ftpClient.sendNoOp();//
        } catch (IOException e) {
            logger.error("Failed to validate client ", e);
            return false;
        }
    }

    public FTPConfig getConfig() {
        return config;
    }
}
